//
// Created by xbm on 23-3-6.
//

#ifndef WEBSERVER_LOGWRITER_H
#define WEBSERVER_LOGWRITER_H
#include <thread>
#include <string>
#include <chrono>
#include <iostream>

#include "fileUtil.h"
#include "buffer.h"

using namespace std;

namespace logging::logWriter {
class AscynLogWriter {
public:
    void run() {
        using namespace buffer;
        while (!closed) {
            buffer_pool_.waitForBuffer(1000);
            while (buffer_pool_.hasUsedBuffer()) {
                Buffer &buffer = buffer_pool_.getUsedBuffer();
                file.append(buffer.getData());
                buffer.reset();
                buffer_pool_.moveUsed();
            }
        }
        closed= false;
    }

    AscynLogWriter(const string &filename): file(filename) {
        thread t(&AscynLogWriter::run, this);
        t.detach();
    }

    void write(string_view sv){
        buffer_pool_.write(sv);
    }

    ~AscynLogWriter() {
        closed = true;
        while (closed)this_thread::yield();
    }

private:
    bool closed = false;
    buffer::BufferPool buffer_pool_;
    fileUtil::AppendFile file;



};
}
#endif //WEBSERVER_LOGWRITER_H
